<template>
    <div class="detail-page">
        <el-page-header content="进货单详情" @back="handleClose" class="detail-header" />

        <!-- 上面卡片：基础信息（明细） -->
        <el-card class="detail-card info-card" shadow="never">
            <!-- 顶部标题和操作区域 -->
            <div class="header-section">
                <div class="title-area">
                    <span class="order-label">进货单号:</span>
                    <span class="order-number">{{ stockinForm.stockinGoodsNo || '--' }}</span>
                    <el-tag :type="getStatusTagType(stockinForm.stockinGoodsStatus)" size="default" class="status-tag">
                        {{ getStatusText(stockinForm.stockinGoodsStatus) }}
                    </el-tag>
                </div>
                <div class="action-buttons">
                    <el-button type="primary" @click="handleEdit" size="small">编辑</el-button>
                    <el-button @click="handleCopy" size="small">复制</el-button>
                    <el-button @click="handlePrint" size="small">打印</el-button>
                    <el-button type="danger" @click="handleDelete" size="small">删除</el-button>
                </div>
            </div>

            <!-- 基础信息 - 第一张图片的字段 -->
            <div class="info-content">
                <el-descriptions :column="4" border>
                    <el-descriptions-item label="制单人">
                        <span class="info-value">{{ stockinForm.stockinUser || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="进货日期">
                        <span class="info-value">{{ formatDate(stockinForm.stockinGoodsDate) }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="联系方式">
                        <span class="info-value">{{ stockinForm.stockinContactPhone || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="备注">
                        <span class="info-value">{{ stockinForm.remark || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="3" border class="info-row">
                    <el-descriptions-item label="所在部门">
                        <span class="info-value">{{ stockinForm.stockinDepartment || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="供应商">
                        <span class="info-value">{{ stockinForm.supplierName || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="进货部门">
                        <span class="info-value">{{ stockinForm.organizationName || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>

                <el-descriptions :column="3" border class="info-row">
                    <el-descriptions-item label="制单时间">
                        <span class="info-value">{{ formatDateTime(stockinForm.stockinTime) }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="联系人">
                        <span class="info-value">{{ stockinForm.stockinContact || '-' }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="进货人">
                        <span class="info-value">{{ stockinForm.userName || '-' }}</span>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </el-card>

        <!-- 下面卡片：标签页（记录） -->
        <el-card class="detail-card tabs-card" shadow="never">
            <div class="tabs-section">
                <el-tabs v-model="activeTab" type="card" class="detail-tabs" @tab-change="handleTabChange">
                    <el-tab-pane label="其他信息" name="other">
                        <div class="tab-content">
                            <el-descriptions :column="2" border class="other-info-descriptions">
                                <el-descriptions-item label="供应商" :span="1">
                                    <span class="info-value">{{ stockinForm.supplierName || '-' }}</span>
                                </el-descriptions-item>
                                <el-descriptions-item label="联系人" :span="1">
                                    <span class="info-value">{{ stockinForm.stockinContact || '-' }}</span>
                                </el-descriptions-item>
                                <el-descriptions-item label="制单备注" :span="1">
                                    <span class="info-value">{{ stockinForm.remark || '-' }}</span>
                                </el-descriptions-item>
                                <el-descriptions-item label="联系电话" :span="1">
                                    <span class="info-value">{{ stockinForm.stockinContactPhone || '-' }}</span>
                                </el-descriptions-item>
                                <el-descriptions-item label="经办人" :span="1">
                                    <span class="info-value">{{ stockinForm.userName || '-' }}</span>
                                </el-descriptions-item>
                            </el-descriptions>

                            <!-- 附件 -->
                            <div class="section-block">
                                <div class="section-title">附件</div>
                                <div class="attachment-list" v-if="fileList.length > 0">
                                    <el-link v-for="(file, index) in fileList" :key="index" type="primary"
                                        :href="file.url" target="_blank" class="file-link">
                                        {{ file.name }}
                                    </el-link>
                                </div>
                                <div v-else class="empty-attachment">
                                    <el-icon class="attachment-icon">
                                        <Box />
                                    </el-icon>
                                    <span>暂无附件</span>
                                </div>
                            </div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="进货明细" name="details">
                        <div class="tab-content">
                            <el-table :data="stockinDetails" border stripe style="width: 100%"
                                v-loading="detailLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="productName" label="货品名称" min-width="160"
                                    show-overflow-tooltip />
                                <el-table-column prop="productCode" label="货品编号" min-width="140"
                                    show-overflow-tooltip />
                                <el-table-column label="规格" min-width="120" show-overflow-tooltip>
                                    <template #default="{ row }">
                                        {{ row.productUnit || row.specification || '--' }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="单位" min-width="100" show-overflow-tooltip>
                                    <template #default="{ row }">
                                        {{ row.unit || row.productSpecification || '--' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="productTypeName" label="货品类型" min-width="120"
                                    show-overflow-tooltip />
                                <el-table-column prop="currentStock" label="当前库存" width="100" align="right">
                                    <template #default="{ row }">
                                        {{ row.currentStock ?? 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="进货数量" width="120" align="right">
                                    <template #default="{ row }">
                                        {{ row.quantity ?? 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="进货单价" width="120" align="right">
                                    <template #default="{ row }">
                                        ¥{{ Number(row.unitPrice ?? 0).toFixed(2) }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="金额" width="120" align="right">
                                    <template #default="{ row }">
                                        <span class="amount-text">¥{{ Number(row.amount ?? 0).toFixed(2) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip>
                                    <template #default="{ row }">
                                        {{ row.remark || '--' }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="detail-summary" v-if="stockinDetails.length > 0">
                                <span>货品种类：{{ stockinDetails.length }}</span>
                                <span>货品数量：{{ totalQuantity }}</span>
                                <span>总金额：<span class="amount-text">¥{{ totalAmount.toFixed(2) }}</span></span>
                            </div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="入库记录" name="inbound">
                        <div class="tab-content">
                            <el-table :data="inboundRecords" border stripe style="width: 100%"
                                v-loading="inboundLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="warehouseName" label="仓库" min-width="120"
                                    show-overflow-tooltip />
                                <el-table-column prop="productName" label="货品名称" min-width="160"
                                    show-overflow-tooltip />
                                <el-table-column prop="quantity" label="入库数量" width="120" align="right" />
                                <el-table-column prop="inboundTime" label="入库时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.inboundTime) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip />
                            </el-table>
                            <div v-if="inboundRecords.length === 0" class="empty-text">暂无入库记录</div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="退货记录" name="return">
                        <div class="tab-content">
                            <el-table :data="returnRecords" border stripe style="width: 100%" v-loading="returnLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="productName" label="货品名称" min-width="160"
                                    show-overflow-tooltip />
                                <el-table-column prop="quantity" label="退货数量" width="120" align="right" />
                                <el-table-column prop="returnTime" label="退货时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.returnTime) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="reason" label="退货原因" min-width="200" show-overflow-tooltip />
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip />
                            </el-table>
                            <div v-if="returnRecords.length === 0" class="empty-text">暂无退货记录</div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="操作记录" name="operation">
                        <div class="tab-content">
                            <el-table :data="operationRecords" border stripe style="width: 100%"
                                v-loading="operationLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="operationType" label="操作类型" width="120" />
                                <el-table-column prop="operationTime" label="操作时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.operationTime) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip />
                                <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
                            </el-table>
                            <div v-if="operationRecords.length === 0" class="empty-text">暂无操作记录</div>
                        </div>
                    </el-tab-pane>

                    <el-tab-pane label="审核记录" name="approval">
                        <div class="tab-content">
                            <el-table :data="approvalRecords" border stripe style="width: 100%"
                                v-loading="approvalLoading">
                                <el-table-column type="index" label="序号" width="60" />
                                <el-table-column prop="approvalStatus" label="审核状态" width="120">
                                    <template #default="{ row }">
                                        <el-tag :type="row.approvalStatus === '通过' ? 'success' : 'danger'" size="small">
                                            {{ row.approvalStatus }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="approvalTime" label="审核时间" width="160">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.approvalTime) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="approver" label="审核人" width="100" show-overflow-tooltip />
                                <el-table-column prop="remark" label="审核意见" min-width="200" show-overflow-tooltip />
                            </el-table>
                            <div v-if="approvalRecords.length === 0" class="empty-text">暂无审核记录</div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentCopy, Box } from '@element-plus/icons-vue'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

interface InboundRecordRow {
    id?: string | number
    warehouseName: string
    productName: string
    quantity: number
    inboundTime?: string
    operator?: string
}

const route = useRoute()
const router = useRouter()

// 表单数据
const stockinForm = reactive({
    stockinGoodsId: '',
    stockinGoodsNo: '',
    stockinGoodsDate: '',
    stockinGoodsStatus: 0,
    supplierId: '',
    supplierName: '',
    stockinContact: '',
    stockinContactPhone: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    stockinUser: '',
    stockinDepartment: '',
    stockinTime: '',
    remark: '',
})

// 进货明细
const stockinDetails = ref<any[]>([])
const detailLoading = ref(false)

// 附件列表
const fileList = ref<Array<{ name: string; url: string }>>([])

// 自定义字段
const customFields = ref<Array<{ label: string; value: string }>>([])

// 标签页
const activeTab = ref('other')

// 记录数据
const inboundRecords = ref<InboundRecordRow[]>([])
const returnRecords = ref<any[]>([])
const operationRecords = ref<any[]>([])
const approvalRecords = ref<any[]>([])
const inboundLoading = ref(false)
const returnLoading = ref(false)
const operationLoading = ref(false)
const approvalLoading = ref(false)
const rawDetailData = ref<any>(null)

// 计算属性
const totalQuantity = computed(() => {
    return stockinDetails.value.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

const totalAmount = computed(() => {
    return stockinDetails.value.reduce((sum, item) => sum + (item.amount || 0), 0)
})

// 状态相关
const getStatusText = (status: number) => {
    switch (status) {
        case 0:
            return '草稿'
        case 1:
            return '待审核'
        case 2:
            return '部分入库'
        case 3:
            return '已入库'
        case 4:
            return '已关闭'
        case 5:
            return '已作废'
        default:
            return '未知'
    }
}

const getStatusTagType = (status: number) => {
    switch (status) {
        case 3:
            return 'success'
        case 1:
            return 'warning'
        case 4:
        case 5:
            return 'danger'
        default:
            return 'info'
    }
}

// 格式化函数
const formatDate = (date?: string) => {
    if (!date) return '--'
    return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
    if (!date) return '--'
    return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

// 复制单号
const copyOrderNo = () => {
    if (!stockinForm.stockinGoodsNo) return
    navigator.clipboard.writeText(stockinForm.stockinGoodsNo).then(() => {
        ElMessage.success('进货单号已复制到剪贴板')
    }).catch(() => {
        ElMessage.error('复制失败')
    })
}

// 操作按钮
const handleEdit = () => {
    router.push({
        path: '/UpdateStockingGoods',
        query: { stockinGoodsId: stockinForm.stockinGoodsId },
    })
}

const handleDelete = () => {
    ElMessageBox.confirm('确认删除该进货单吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                const res = await myaxios.delete('/api/StockinGoods/DeleteStockinGoods', {
                    params: { stockinGoodsId: stockinForm.stockinGoodsId },
                })
                const result = res.data || {}
                if (result.code === 200) {
                    ElMessage.success(result.message || '删除成功')
                    router.push('/GetStockingGoods')
                } else {
                    ElMessage.error(result.message || '删除失败')
                }
            } catch (error) {
                console.error('删除进货单失败:', error)
                ElMessage.error('删除失败，请稍后重试')
            }
        })
        .catch(() => { })
}

const handleClose = () => {
    router.push('/GetStockingGoods')
}

const handleAudit = () => {
    ElMessage.warning('审核功能暂未实现')
}

const handleCopy = () => {
    ElMessage.warning('复制功能暂未实现')
}

const handlePrint = () => {
    ElMessage.warning('打印功能暂未实现')
}

// 应用基础信息
const applyStockinBaseInfo = (data: any) => {
    Object.assign(stockinForm, {
        stockinGoodsId: data.stockinGoodsId || data.id || '',
        stockinGoodsNo: data.stockinGoodsNo || '',
        stockinGoodsDate: data.stockinGoodsDate || '',
        stockinGoodsStatus: data.stockinGoodsStatus ?? 0,
        supplierId: data.supplierId || '',
        supplierName: data.supplierName || '',
        stockinContact: data.stockinContact || '',
        stockinContactPhone: data.stockinContactPhone || '',
        organizationId: data.organizationId || '',
        organizationName: data.organizationName || '',
        userId: data.userId || '',
        userName: data.userName || '',
        stockinUser: data.stockinUser || data.userName || '',
        stockinDepartment: data.stockinDepartment || data.organizationName || '',
        stockinTime: data.stockinTime || data.createrTime || '',
        remark: data.remark || data.stockinRemark || '',
    })
}

// 提取明细列表
const extractDetailList = (data: any): any[] => {
    const candidates = [
        data?.goodsDetails,
        data?.stockinGoodsDetails,
        data?.details,
        data?.detailList,
        data?.items,
        data?.data,
    ]

    for (const candidate of candidates) {
        if (Array.isArray(candidate) && candidate.length > 0) {
            return candidate
        }
        if (typeof candidate === 'string') {
            try {
                const parsed = JSON.parse(candidate)
                if (Array.isArray(parsed) && parsed.length > 0) {
                    return parsed
                }
            } catch (e) {
                // 忽略解析错误
            }
        }
    }
    return []
}

// 转换明细数据
const transformDetailResponse = (detail: any) => {
    return {
        productId: detail.productId || '',
        productName: detail.productName || '',
        productCode: detail.productCode || '',
        productUnit: detail.specificationModel || detail.productUnit || '',
        specification: detail.specificationModel || detail.productSpecification || '',
        unit: detail.unitName || detail.unit || '',
        productSpecification: detail.unitName || detail.unit || '',
        productTypeName: detail.productTypeName || '',
        currentStock: detail.currentInventory || detail.currentStock || 0,
        quantity: detail.quantity || 0,
        unitPrice: detail.purchasePrice || detail.unitPrice || 0,
        amount: detail.amount || 0,
        remark: detail.remark || '',
    }
}

const normalizeToArray = (value: any): any[] => {
    if (!value) return []
    if (Array.isArray(value)) return value
    if (typeof value === 'string') {
        try {
            const parsed = JSON.parse(value)
            return Array.isArray(parsed) ? parsed : []
        } catch (error) {
            return []
        }
    }
    if (typeof value === 'object') {
        const nestedKeys = ['data', 'list', 'items', 'rows', 'records', 'detailList', 'details']
        for (const key of nestedKeys) {
            const candidate = (value as any)[key]
            if (Array.isArray(candidate)) return candidate
        }
        return [value]
    }
    return []
}

const attachParentMeta = (detail: any, parent?: any) => {
    if (!parent || typeof detail !== 'object') return detail
    return {
        ...detail,
        __parentWarehouse:
            parent?.warehouseName || parent?.warehouse || parent?.wareHouseName || parent?.locationName || parent?.storagelocationName,
        __parentOperator:
            parent?.operator || parent?.userName || parent?.handler || parent?.createUser || parent?.documentCreator || parent?.makerName,
        __parentTime:
            parent?.storageDate || parent?.inboundTime || parent?.receiptDate || parent?.createTime || parent?.documentCreation,
    }
}

const flattenParentDetails = (parents: any[]) => {
    const result: any[] = []
    parents.forEach((parent) => {
        const detailCandidates = [
            normalizeToArray(parent?.details),
            normalizeToArray(parent?.detailList),
            normalizeToArray(parent?.items),
            normalizeToArray(parent?.warehousingDetails),
            normalizeToArray(parent?.inboundDetails),
        ]
        const details = detailCandidates.find((list) => list.length) || []
        details.forEach((detail) => {
            result.push(attachParentMeta(detail, parent))
        })
    })
    return result
}

const inboundDetailKeys = [
    'inboundRecords',
    'inboundDetails',
    'inboundDetailList',
    'inboundGoodsDetails',
    'stockinInboundDetails',
    'stockinWarehousingDetails',
    'stockinReceiptDetails',
    'stockinRecordDetails',
    'warehousingDetails',
    'warehousingDetailList',
    'warehousingDetail',
    'receiptDetails',
    'receiptDetailList',
    'receiptGoodsDetails',
    'warehousingList',
]

const extractInboundDetailsFromContainer = (container: any): any[] => {
    if (!container || typeof container !== 'object') return []
    for (const key of inboundDetailKeys) {
        if (!(key in container)) continue
        if (key === 'warehousingList') {
            const parents = normalizeToArray(container[key])
            if (!parents.length) continue
            const flattened = flattenParentDetails(parents)
            if (flattened.length) return flattened
            continue
        }
        const details = normalizeToArray(container[key])
        if (details.length) {
            return details.map((detail) => attachParentMeta(detail, container))
        }
    }
    return []
}

const extractInboundDetailsFromData = (raw: any): any[] => {
    if (!raw) return []
    if (Array.isArray(raw)) {
        for (const item of raw) {
            const details = extractInboundDetailsFromContainer(item)
            if (details.length) return details
        }
        return []
    }
    const containers: any[] = [raw]
    const nestedKeys = ['data', 'result', 'value', 'payload', 'stockinGoods', 'baseInfo', 'extra', 'extend', 'extData']
    nestedKeys.forEach((key) => {
        const candidate = raw?.[key]
        if (candidate && typeof candidate === 'object') {
            containers.push(candidate)
        }
    })
    for (const container of containers) {
        const details = extractInboundDetailsFromContainer(container)
        if (details.length) return details
    }
    return []
}

const normalizeInboundRecord = (item: any): InboundRecordRow => {
    const quantitySource = [
        item?.quantity,
        item?.actualQuantity,
        item?.inboundQuantity,
        item?.inQty,
        item?.stockinQuantity,
        item?.warehousingNum,
        item?.newInputNum,
        item?.inputQty,
        item?.totalQuantity,
    ]
    const quantity =
        quantitySource
            .map((val) => Number(val))
            .find((val) => Number.isFinite(val) && !Number.isNaN(val)) ?? 0

    const inboundTime =
        item?.inboundTime ||
        item?.storageDate ||
        item?.receiptDate ||
        item?.inputTime ||
        item?.createTime ||
        item?.documentCreation ||
        item?.__parentTime ||
        stockinForm.stockinGoodsDate ||
        stockinForm.stockinTime ||
        ''

    return {
        id:
            item?.id ||
            item?.detailId ||
            item?.warehousingDetailId ||
            item?.recordId ||
            item?.stockinGoodsDetailId ||
            item?.productId ||
            item?.productCode,
        warehouseName:
            item?.warehouseName ||
            item?.wareHouseName ||
            item?.warehouse ||
            item?.locationName ||
            item?.storagelocationName ||
            item?.__parentWarehouse ||
            stockinForm.organizationName ||
            stockinForm.stockinDepartment ||
            '-',
        productName: item?.productName || item?.goodsName || item?.product || '-',
        quantity,
        inboundTime,
        operator:
            item?.operator ||
            item?.handler ||
            item?.userName ||
            item?.createUser ||
            item?.documentCreator ||
            item?.makerName ||
            item?.__parentOperator ||
            stockinForm.userName ||
            stockinForm.stockinUser ||
            '',
    }
}

const buildInboundRecordsFromStockinDetails = (): InboundRecordRow[] => {
    if (!stockinDetails.value.length) return []
    return stockinDetails.value.map((detail, index) => ({
        id: detail.productId || detail.productCode || index,
        warehouseName: detail.warehouseName || stockinForm.organizationName || stockinForm.stockinDepartment || '-',
        productName: detail.productName || '-',
        quantity: Number(detail.quantity ?? detail.stockinQuantity ?? 0),
        inboundTime: stockinForm.stockinGoodsDate || stockinForm.stockinTime || '',
        operator: stockinForm.userName || stockinForm.stockinUser || '',
    }))
}

const syncInboundRecordsFromRaw = (raw?: any) => {
    const details = extractInboundDetailsFromData(raw ?? rawDetailData.value)
    if (details.length) {
        inboundRecords.value = details.map((item) => normalizeInboundRecord(item))
    } else if (stockinDetails.value.length) {
        inboundRecords.value = buildInboundRecordsFromStockinDetails()
    } else {
        inboundRecords.value = []
    }
}

// 加载进货单详情
const loadStockinGoodsDetail = async (id: string | number) => {
    if (!id) return
    detailLoading.value = true
    try {
        let res = await myaxios
            .get('/api/StockinGoods/GetStockingoodsDetail', {
                params: { stockinGoodsId: id },
            })
            .catch(() => null)
        if (!res) {
            res = await myaxios.get('/api/StockinGoods/GetStockinGoodsDetail', {
                params: { stockinGoodsId: id },
            })
        }
        if (!res) {
            ElMessage.error('获取进货详情失败')
            return
        }
        const result = res.data || {}
        if (result.code === 200) {
            const data = result.data || {}
            rawDetailData.value = data
            const baseInfo = data.stockinGoods || data.baseInfo || data
            applyStockinBaseInfo(baseInfo)

            // 处理明细
            const detailList = extractDetailList(data)
            stockinDetails.value = detailList.map((item: any) => transformDetailResponse(item))
            syncInboundRecordsFromRaw(data)

            // 处理附件
            if (data.files && Array.isArray(data.files)) {
                fileList.value = data.files.map((file: any) => ({
                    name: file.fileName || file.name,
                    url: file.fileUrl || file.url,
                }))
            }

            // 处理自定义字段（如果有）
            if (data.customFields && Array.isArray(data.customFields)) {
                customFields.value = data.customFields
            }
        } else {
            ElMessage.error(result.message || '获取进货详情失败')
        }
    } catch (error) {
        console.error('获取进货详情失败:', error)
        ElMessage.error('获取进货详情失败，请稍后重试')
    } finally {
        detailLoading.value = false
    }
}

// 加载记录数据（占位函数，后续可对接真实接口）
const loadInboundRecords = async () => {
    inboundLoading.value = true
    try {
        syncInboundRecordsFromRaw()
    } finally {
        inboundLoading.value = false
    }
}

const loadReturnRecords = async () => {
    returnLoading.value = true
    // TODO: 对接真实接口
    setTimeout(() => {
        returnRecords.value = []
        returnLoading.value = false
    }, 500)
}

const loadOperationRecords = async () => {
    operationLoading.value = true
    // TODO: 对接真实接口
    setTimeout(() => {
        operationRecords.value = []
        operationLoading.value = false
    }, 500)
}

const loadApprovalRecords = async () => {
    approvalLoading.value = true
    // TODO: 对接真实接口
    setTimeout(() => {
        approvalRecords.value = []
        approvalLoading.value = false
    }, 500)
}

// 标签页切换时加载对应数据
const handleTabChange = (tabName: string) => {
    if (tabName === 'inbound' && inboundRecords.value.length === 0) {
        loadInboundRecords()
    } else if (tabName === 'return' && returnRecords.value.length === 0) {
        loadReturnRecords()
    } else if (tabName === 'operation' && operationRecords.value.length === 0) {
        loadOperationRecords()
    } else if (tabName === 'approval' && approvalRecords.value.length === 0) {
        loadApprovalRecords()
    }
}

// 从缓存读取数据并立即显示
const preloadFromCache = () => {
    const STOCKIN_DETAIL_CACHE_KEY = 'STOCKIN_DETAIL_CACHE'
    try {
        const cacheText = sessionStorage.getItem(STOCKIN_DETAIL_CACHE_KEY)
        if (cacheText) {
            const cached = JSON.parse(cacheText)
            applyStockinBaseInfo(cached)
            // 清除缓存
            sessionStorage.removeItem(STOCKIN_DETAIL_CACHE_KEY)
        }
    } catch (error) {
        console.warn('读取缓存数据失败:', error)
    }
}

onMounted(() => {
    const stockinGoodsId = route.query.stockinGoodsId
    if (stockinGoodsId) {
        // 先从缓存读取数据，立即显示
        preloadFromCache()
        // 然后从后端获取最新数据
        const id = Array.isArray(stockinGoodsId) ? stockinGoodsId[0] : stockinGoodsId
        loadStockinGoodsDetail(String(id))
    } else {
        ElMessage.error('缺少进货单ID')
        router.push('/GetStockingGoods')
    }
})
</script>

<style scoped>
.detail-page {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
}

.detail-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-bottom: 16px;
}

.detail-card:last-child {
    margin-bottom: 0;
}

.detail-card :deep(.el-card__body) {
    padding: 24px;
}

.info-card {
    margin-bottom: 16px;
}

.tabs-card {
    margin-top: 0;
}

/* 顶部标题和操作区域 */
.header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.title-area {
    display: flex;
    align-items: center;
    gap: 12px;
}

.title {
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    margin: 0;
    line-height: 1.5;
}

.copy-icon {
    cursor: pointer;
    color: #409eff;
    font-size: 18px;
    transition: color 0.3s;
    flex-shrink: 0;
}

.copy-icon:hover {
    color: #66b1ff;
}

.action-area {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-shrink: 0;
}

.status-info {
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
}

.status-label {
    color: #606266;
    font-size: 14px;
    font-weight: 500;
}

.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.action-buttons .el-button {
    min-width: 70px;
}

/* 信息内容 */
.info-content {
    margin-top: 0;
}

.info-row {
    margin-top: 0;
}

.info-row :deep(.el-descriptions__table) {
    border-top: none;
}

.info-value {
    color: #303133;
    font-size: 14px;
    word-break: break-word;
}

:deep(.el-descriptions) {
    margin-bottom: 0;
}

:deep(.el-descriptions__label) {
    color: #909399;
    font-weight: 500;
    background-color: #fafafa;
    width: 120px;
    text-align: right;
    padding-right: 16px;
}

:deep(.el-descriptions__content) {
    color: #303133;
    background-color: #fff;
    padding-left: 16px;
}

:deep(.el-descriptions__table) {
    width: 100%;
}

:deep(.el-descriptions__table .el-descriptions__cell) {
    padding: 12px 0;
}

/* 标签页区域 */
.tabs-section {
    margin-top: 24px;
}

.detail-tabs {
    margin-top: 0;
}

:deep(.el-tabs__content) {
    padding-top: 0;
}

.tab-content {
    padding: 20px 0;
}

/* 其他信息样式 */
.other-info-descriptions {
    margin-bottom: 32px;
}

.section-block {
    margin-bottom: 32px;
}

.section-block:last-child {
    margin-bottom: 0;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 16px 0;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;
    line-height: 1.5;
}

.empty-attachment {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;
    color: #909399;
    font-size: 14px;
}

.attachment-icon {
    font-size: 48px;
    color: #c0c4cc;
    margin-bottom: 12px;
}

.attachment-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: center;
}

.file-link {
    padding: 8px 16px;
    background: #f0f9ff;
    border: 1px solid #b3d8ff;
    border-radius: 4px;
    text-decoration: none;
    display: inline-block;
    transition: all 0.3s;
    font-size: 14px;
}

.file-link:hover {
    background: #e1f3ff;
    border-color: #409eff;
    transform: translateY(-1px);
}

.custom-fields-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
}

.custom-field-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    background: #fafafa;
    border-radius: 4px;
    min-height: 44px;
}

.field-label {
    color: #909399;
    font-size: 14px;
    min-width: 120px;
    font-weight: 500;
    flex-shrink: 0;
}

.field-value {
    color: #303133;
    font-size: 14px;
    flex: 1;
    word-break: break-word;
}

.empty-text {
    color: #909399;
    font-size: 14px;
    text-align: center;
    padding: 40px 0;
}

/* 明细汇总 */
.detail-summary {
    margin-top: 16px;
    padding: 16px 20px;
    background: #f5f7fa;
    border-radius: 4px;
    display: flex;
    gap: 32px;
    color: #606266;
    font-size: 14px;
    align-items: center;
    flex-wrap: wrap;
}

.detail-summary span {
    white-space: nowrap;
}

.amount-text {
    font-weight: 600;
    color: #f56c6c;
}

/* 表格样式优化 */
:deep(.el-table) {
    font-size: 13px;
}

:deep(.el-table th) {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
    padding: 12px 0;
    text-align: center;
}

:deep(.el-table td) {
    padding: 12px 0;
    text-align: center;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background-color: #fafafa;
}

:deep(.el-table .el-table__row:hover > td) {
    background-color: #f5f7fa !important;
}

/* 标签页样式 */
:deep(.el-tabs--card > .el-tabs__header) {
    border-bottom: 1px solid #dcdfe6;
    margin-bottom: 20px;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
    border: 1px solid #dcdfe6;
    border-bottom: none;
    font-size: 14px;
    font-weight: 500;
    color: #606266;
    background: #fafafa;
    margin-right: 4px;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
    color: #409eff;
    background: #fff;
    border-bottom: 1px solid #fff;
}

:deep(.el-tabs--card > .el-tabs__header .el-tabs__item:hover) {
    color: #409eff;
}

/* 响应式 */
@media (max-width: 768px) {
    .header-section {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
    }

    .action-area {
        width: 100%;
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }

    .action-buttons {
        flex-wrap: wrap;
        width: 100%;
    }

    .custom-fields-grid {
        grid-template-columns: 1fr;
    }

    .detail-card :deep(.el-card__body) {
        padding: 16px;
    }
}
</style>
